import React, { useRef } from 'react';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Button, Tag, Space, Menu, Dropdown } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { request } from 'umi';
import { api } from '@/global';
import { render } from 'react-dom';
import Field from '@ant-design/pro-field';
import PDFRender from '@/components/PDFRender';
import DOCXRender from '@/components/DOCXRender';
import dayjs from 'dayjs';
import { bind } from 'lodash';

const downloadFile = (data, fileName) => {
  if (!data) {
    return;
  }
  const url = window.URL.createObjectURL(new Blob([data]));
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', fileName + '.pdf');
  document.body.appendChild(link);
  link.click();
};

type fileManagerType = {
  fileId: string;
  fileName: string;
  fileSuffix: string;
  filePathName: string;
  fileBucketName: string;
  createTime: string;
  fileOwnerName: string;
  isDelete: number;
  fileDescribe: string;
  fileOssPath: string;
  fileRealName: string;
  fileType: number;
  fileStorageName: string;
  fileDownload: number;
};

const columns: ProColumns<fileManagerType>[] = [
  {
    dataIndex: 'fileId',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '文件名称',
    dataIndex: 'fileName',
  },
  {
    title: '文件描述',
    dataIndex: 'fileDescribe',
    search: false,
  },
  {
    title: '文件真实名称',
    dataIndex: 'fileRealName',
  },
  {
    title: '文件负责人',
    dataIndex: 'fileOwnerName',
    request: async () => {
      const list: any[] = [];
      const result = await request(api.getSimpleUserInfo);
      list.push({ label: '全部', value: 0 });
      result.data.forEach((item) => {
        list.push({ label: item.name, value: item.id });
      });

      return list;
    },
  },

  {
    title: '文件类型',
    dataIndex: 'fileType',
    render: (_, b) => {
      if (b.fileType == 1) {
        return <Tag color={'#13c2c2'}>线上文件</Tag>;
      } else if (b.fileType == 2) {
        return <Tag color={'#fa8c16'}>线下文件</Tag>;
      } else {
        return <Tag color={'#60a3bc'}>审批文件</Tag>;
      }
    },
    request: async () => {
      const list: any[] = [];

      list.push({ label: '全部', value: 0 });
      list.push({ label: '线上文件', value: 1 });
      list.push({ label: '线下文件', value: 2 });
      list.push({ label: '审批文件', value: 3 });
      return list;
    },
  },
  {
    title: '文件下载次数',
    search: false,
    dataIndex: 'fileDownload',
    sorter: (a: fileManagerType, b: fileManagerType) => {
      return a.fileDownload - b.fileDownload;
    },
  },
  {
    title: '文件属性',
    dataIndex: 'fileSuffix',
    request: async () => {
      const list: any[] = [];
      const result = await request(api.getFileAllSuffix);
      list.push({ label: '全部', value: 0 });
      result.data.forEach((item) => {
        list.push({ label: item, value: item });
      });

      return list;
    },
  },
  {
    title: '所属文件筒',
    dataIndex: 'fileBucketName',

    request: async () => {
      const list: any[] = [];
      const result = await request(api.getBucketInfo);
      list.push({ label: '全部', value: 0 });
      result.data.forEach((item) => {
        list.push({ label: item.bucketName, value: item.id });
      });

      return list;
    },
  },
  {
    title: '所属文件夹',
    search: false,
    dataIndex: 'filePathName',
  },
  {
    title: '所属存储室',

    dataIndex: 'fileStorageName',
    request: async () => {
      const list: any[] = [];
      const result = await request(api.getStorageList);
      list.push({ label: '全部', value: 0 });
      result.data.forEach((item) => {
        list.push({ label: item.title, value: item.id });
      });

      return list;
    },
  },
  {
    title: '是否删除',
    dataIndex: 'isDelete',
    request: async () => {
      const list: any[] = [];

      list.push({ label: '全部', value: -1 });
      list.push({ label: '未删除', value: 0 });
      list.push({ label: '已删除', value: 1 });
      return list;
    },
    render: (_, b) => {
      if (b.isDelete == 0) {
        return <Tag color={'#12b886'}>存在</Tag>;
      } else {
        return <Tag color={'#e8590c'}>已删除</Tag>;
      }
    },
  },
  {
    title: '文件创建时间',
    search: false,
    dataIndex: 'createTime',
    render: (_, b) => {
      console.log(b.createTime);

      return <div>{dayjs(b.createTime).format('YYYY/MM/DD')}</div>;
    },
    sorter: (a: fileManagerType, b: fileManagerType) => {
      const acreate = dayjs(a.createTime).valueOf();
      const bcreate = dayjs(b.createTime).valueOf();
      return acreate - bcreate;
    },
  },
  {
    title: '文件预览',
    dataIndex: 'fileOssPath',
    search: false,
    render: (_, b) => {
      if (b.fileType == 2) {
        return <Field text={b.fileOssPath} valueType="image" mode={'read'} plain={false} />;
      } else {
        if (b.fileSuffix === 'pdf') {
          return <PDFRender key={b.fileOssPath} url={b.fileOssPath} title="预览" />;
        }

        if (b.fileSuffix === 'docx') {
          return <DOCXRender key={b.fileOssPath} url={b.fileOssPath} title="预览" />;
        }
        if (b.fileSuffix === 'png' || b.fileSuffix === 'jpg' || b.fileSuffix === 'jpeg') {
          return <Field text={b.fileOssPath} valueType="image" mode={'read'} plain={false} />;
        }
      }

      return <div></div>;
    },
  },
  {
    title: '下载',
    search: false,
    width: 50,
    render: (_, b) => {
      if (b.fileType == 1) {
        return (
          <a
            key={b.fileOssPath}
            onClick={() => {
              request(api.addFileDownload, {
                params: {
                  id: b.fileId,
                },
              });

              if (b.fileSuffix === 'pdf') {
                downloadFile(b.fileOssPath, b.fileName);
              } else {
                window.open(b.fileOssPath);
              }
            }}
          >
            下载
          </a>
        );
      } else {
        return <div></div>;
      }
    },
  },
];

export default () => {
  const actionRef = useRef<ActionType>();
  return (
    <ProTable<fileManagerType>
      columns={columns}
      actionRef={actionRef}
      request={async (params = {}, sort, filter) => {
        console.log(params);

        const result = await request<fileManagerType[]>(api.getComplexFileInfo, {
          method: 'POST',
          data: {
            ...params,
          },
        });

        return result;
      }}
      editable={{
        type: 'multiple',
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
      }}
      rowKey="fileId"
      search={{
        collapsed: false,
        collapseRender: () => {
          return <div></div>;
        },
      }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 15,
      }}
      dateFormatter="string"
      headerTitle="所有文件信息"
      toolBarRender={() => []}
    />
  );
};
